import XLSX from 'xlsx';
import { exportExcl } from '@/utils/xlsx';
import { message } from 'antd';
import { queryPage, create, exportQrcode, remove, createArr } from '@/pages/data/qr_code/service';
import { queryDictList } from '@/services/dict';

export default {
  namespace: 'qr_code',

  state: {
    list: { data: [] },
    positionList: { data: [] },
    details: [],
    cond: {},
    dict: {}
  },

  effects: {
    *queryPage({ payload = { pageNum: 1 } }, { call, put, select }) {
      const cond = yield select(state => state.qr_code.cond);
      const params = { ...payload, ...cond };
      if (!params.pageSize) params.pageSize = 10;
      const { list = [], total } = yield call(queryPage, params);
      yield put({ type: 'setPage', payload: { list, total } })
    },
    *updateCond({ payload }, { put }) {
      yield put({ type: 'setCond', payload: payload });
      yield put({ type: 'queryPage' });
    },
    *queryDict({ payload }, { call, put }) {
      const dict = yield call(queryDictList, payload);
      yield put({ type: 'setDict', payload: dict })
    },
    *exportQrcode({ payload }, { call }) {
      const response = yield call(exportQrcode, payload.ids);

      const ans = response && Array.isArray(response) && response.map(item => ({
        '二维码名称': item.name,
        '安装位置': item.installLocation,
        '二维码地址': item.code,
        '生成方式': item.generationModeName,
        '操作人员': item.creatorName,
        '操作时间': item.createTime,
      }));

      exportExcl({
        XLSX,
        data: ans,
        name: "二维码导出",
        fileName: "二维码导出"
      })
    },
    *create({ payload }, { call, put }) {
      const ans = yield call(create, payload);
      if (ans) {
        message.success(ans);
        yield put({ type: 'queryPage' });
      }
    },
    *createArr({ payload }, { call, put }) {
      const ans = yield call(createArr, payload);
      if (ans) {
        message.success(ans);
        yield put({ type: 'queryPage' });
      }
    },
    *remove({ payload }, { call, put }) {
      yield call(remove, payload)
    },
  },

  reducers: {
    setPage(state, action) {
      return {
        ...state,
        list: {
          data: action.payload.list,
          dataCnt: action.payload.total
        }
      }
    },
    setCond(state, action) {
      return {
        ...state,
        cond: action.payload
      }
    },
    setDict(state, action) {
      return {
        ...state,
        dict: action.payload
      }
    },
  }
}
